/*
============================================================================
 Name        : Id3v1Tag.cpp
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : CId3v1Tag implementation
============================================================================
*/

#include "Id3v1Tag.h"
#include "PluginUtility.h"

#include <f32file.h>

CId3v1Tag::CId3v1Tag()
: iPos(0)
{
}

CId3v1Tag::~CId3v1Tag()
{
	DELETE(iTitle);
	DELETE(iArtist);
	DELETE(iAlbum);
}

CId3v1Tag* CId3v1Tag::NewLC(const TDesC& aFileName)
{
	CId3v1Tag* self = new (ELeave)CId3v1Tag();
	CleanupStack::PushL(self);
	self->ConstructL(aFileName);
	return self;
}

CId3v1Tag* CId3v1Tag::NewL(const TDesC& aFileName)
{
	CId3v1Tag* self=CId3v1Tag::NewLC(aFileName);
	CleanupStack::Pop(); // self;
	return self;
}

void CId3v1Tag::ConstructL(const TDesC& aFileName)
{
	DoConstructL(aFileName);
}

void CId3v1Tag::DoConstructL(const TDesC& aFileName)
{
	RFs fs;

	User::LeaveIfError(fs.Connect());
	//CleanupClosePushL(fs);

	RFile file;
	User::LeaveIfError(file.Open(fs, aFileName, EFileRead));

	TInt size;
	file.Size(size);

	//Check size
	if (size < 128) User::Leave(KErrNoMetada);

	TBuf8<KTagBufLen> buf;

	//Read last 128 bytes
	User::LeaveIfError(file.Read(size - 128, buf, 128));

	fs.Close();

	//tag
	TPtr8 tag = buf.LeftTPtr(3);

	//Check if tag is 'TAG'
	tag.UpperCase();
	if (tag.Compare(_L8("TAG")) != 0)  User::Leave(KErrNoMetada);

	//Start reading
	iPos = 3;

	iTitle = ReadL(buf, 30);
	iArtist = ReadL(buf, 30);
	iAlbum = ReadL(buf, 30);

}

HBufC* CId3v1Tag::ReadL(TBuf8<KTagBufLen> aBuf, TInt aLength)
{
	TPtr8 ptr = aBuf.MidTPtr(iPos, aLength);
	TInt nullCharPos = ptr.Locate('\0');
	if (nullCharPos != KErrNotFound) 
	{
		ptr.SetLength(nullCharPos);
	}
	iPos += aLength;

	HBufC* res = HBufC::NewL(ptr.Length());
	res->Des().Copy(ptr);

	return res;
}